<template>
  <div v-if="item" class="drawerTemplateData">
    <div
      v-if="
        (item.type === 'common' || item.type === 'settingWrite') &&
        item.list &&
        item.list.length
      "
      class="drawerTemplateData-view-common"
    >
      <DrawerTemplatePrice
        v-if="
          !props.isPrint && item.type !== 'box' && item.type !== 'settingWrite'
        "
        :data="item"
      />

      <div
        :class="[
          'drawerTemplateData-view-content',
          `${
            item.type === 'settingWrite'
              ? 'drawerTemplateData-view-content-setting'
              : ''
          }`
        ]"
      >
        <div
          v-for="(lItem, lKey) in item.list"
          :key="lKey"
          :class="[
            'drawerTemplateData-view-item',
            `${lItem.isBlock ? 'drawerTemplateData-view-item-block' : ''}`
          ]"
        >
          <div
            v-if="!lItem.hiddenLabel"
            class="drawerTemplateData-view-item-input drawerTemplateData-view-item-label"
          >
            {{ getLabelFn(lItem) }}
          </div>

          <DrawerTemplateInput ref="drawerTemplateInputRef" :data="lItem" />

          <!-- <div
            v-if="lItem.list && lItem.list.length"
            class="drawerTemplateData-view-item-list"
          >
            <div
              v-for="(sItem, sKey) in lItem.list"
              :key="sKey"
              class="drawerTemplateData-view-item-input drawerTemplateData-view-item-input-margin"
            >
              <div
                v-if="sItem.inputType === 'read'"
                class="drawerTemplateData-view-item-input-read"
              >
                <div class="drawerTemplateData-view-item-input-read-val">
                  {{ getReadFn(sItem) }}
                </div>
              </div>
              <div
                v-if="
                  sItem.inputType === 'write' ||
                  sItem.inputType === 'confirmWrite'
                "
                class="drawerTemplateData-view-item-input-write"
              >
                <InputNumber
                  class="drawerTemplateData-view-item-input-write-number"
                  placeholder="请输入"
                  :min="0"
                  :max="999999999"
                  :iconSize="28"
                  :showReduce="false"
                  :showAdd="false"
                  :defaultValue="sItem.value"
                  :precision="1"
                  :onUpdateValue="
                    val => {
                      inputUpdateFn(val, sItem);
                    }
                  "
                  :timer="
                    sItem.blurChange
                      ? null
                      : sItem.inputType === 'write'
                      ? 2000
                      : null
                  "
                  @timeChange="writeFn(sItem, lItem.list)"
                  @blur="
                    e => {
                      inputBlurFn(e, sItem, lItem.list);
                    }
                  "
                />

                <n-button
                  v-if="sItem.inputType === 'confirmWrite'"
                  class="drawerTemplateData-view-item-input-write-number-confirm"
                  type="primary"
                  @click="btnClickFn(sItem, lItem.list)"
                >
                  {{ $t('common.button.primary') }}
                </n-button>
              </div>

              <div
                v-if="sItem.inputType === 'btn' || sItem.inputType === 'btnBool'"
                class="drawerTemplateData-view-item-input-btn"
              >
                <n-button type="primary" @click="btnClickFn(sItem, lItem.list)">
                  {{ getLabelFn(sItem) }}
                </n-button>
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </div>

    <div
      v-if="
        (item.type === 'btn' ||
          item.type === 'box' ||
          item.type === 'slider') &&
        item.list &&
        item.list.length
      "
      :class="[
        'drawerTemplateData-view-btn',
        `${
          item.hiddenBottomBorder
            ? 'drawerTemplateData-view-btn-hidden-bottom-border'
            : ''
        }`
      ]"
    >
      <!-- <div
        v-if="item.showLabel"
        class="drawerTemplateData-view-item-input drawerTemplateData-view-item-label"
      >
        {{ getLabelFn(item) }}
      </div> -->
      <DrawerTemplateInput ref="drawerTemplateInputRef" :data="item" :isBox="item.type === 'box'" />

      <!-- <n-button
        v-for="(lItem, lKey) in item.list"
        :key="lKey"
        type="primary"
        @click="btnClickFn(lItem, item.list)"
      >
        {{ getLabelFn(lItem) }}
      </n-button> -->
    </div>
  </div>
</template>

<script lang="ts" setup name="DrawerTemplateData">
import DrawerTemplatePrice from './DrawerTemplatePrice.vue';

import DrawerTemplateInput from './DrawerTemplateInput.vue';

// import InputNumber from './InputNumber.vue';

import { useMixins } from '@/hooks/useMixins';

// import { filterWriteObjFn } from '@/utils/dfModbus/data';

import { storage } from '@/utils/Storage';

import { getComputedValFn } from './../../options/utils';

type Props = {
  data?: any;
  isPrint?: Boolean;
  parentData?: any;
};

const drawerTemplateInputRef: any = ref(null);

const props = withDefaults(defineProps<Props>(), {
  data: () => null,
  isPrint: () => false,
  parentData: () => null
});

// const message = window['$message'];

// const provitClickFn: any = inject('provitClickFn');

const { language } = useMixins();

// const modbusData: any = inject('modbusData');

const modbusNewData: any = inject('modbusNewData',ref({}));

const item: any = ref(null);

const getLocalByFunId = (funId = null) => {
  let val = 0;

  if (funId) {
    const writeData = storage.get('writeData');

    if (writeData && writeData.length) {
      writeData.every(item => {
        if (item.funId === funId) {
          val = item.value || 0;

          return false;
        }

        return true;
      });
    }
  }

  return val;
};

// const setLocalByFunId = (funId = null, val = 0) => {
//   if (funId) {
//     const writeData = storage.get('writeData');

//     if (writeData && writeData.length) {
//       const obj = writeData.find(item => item.funId === funId);

//       if (obj) {
//         obj.value = val;
//       } else {
//         writeData.push({ funId, value: val });
//       }

//       storage.set('writeData', writeData);
//     } else {
//       storage.set('writeData', [{ funId, value: val }]);
//     }
//   }
// };

const lengSelectValue = inject('lengSelectValue', null);

const materialParamList:any = inject('materialParamList', []);

const setDataListFn = (dataList: any = []) => {
  if (dataList && dataList.length && chooseItem && chooseItem.value) {
    const oChooseItem = chooseItem.value;

    for (const item of dataList) {
      const {
        inputType = null,
        funId = null,
        defaultVal = null,
        defaultValGetLocal = false,
        list = [],
        writeVal = null,
        defaultValGetFunId = null,
        defaultValGetOrderField = null,
        writeUpdateListFunIdObjList = null,
        defaultValGetMaterialParamParamCode=null
      } = item;

      if (inputType === 'lengSelect' || inputType === 'lengSelectBit') {
        item.value = lengSelectValue;

        // return;
      }else if (funId) {
        item.value = (inputType === 'btnBool' || inputType === 'textBool' || inputType === 'btnBoolImg') ? true : item.value || 0;

        if (defaultVal !== null) {
          item.value = defaultVal;
        }

        if (writeVal !== null) {
          item.value = writeVal;
        }

        if (defaultValGetFunId !== null) {
          // const value =
          //   modbusData.value.find(item => item.funId === defaultValGetFunId)
          //     ?.value || 0;

          const value = modbusNewData.value[item.funId] || 0

          item.value = value || writeVal || 0;
        } else if (defaultValGetLocal) {
          item.value = getLocalByFunId(funId) || writeVal || item.value || 0;
        }
      }

      if (defaultValGetOrderField && oChooseItem) {
        item.value = oChooseItem[defaultValGetOrderField] || 0;
      } else if (defaultValGetMaterialParamParamCode && materialParamList && materialParamList.value && materialParamList.value.length) {
        const obj = materialParamList.value.find(item => item.paramCode === defaultValGetMaterialParamParamCode);

        if (obj) {
          item.value = obj.sr;
        }
      }

      if (writeUpdateListFunIdObjList && writeUpdateListFunIdObjList.length) {
        for(const uItem of writeUpdateListFunIdObjList){
          const { funId: wFunId = null, computedValInListObj = null } =
          uItem;

          if (wFunId && computedValInListObj) {
            const lObj = dataList.find(lItem => lItem.funId === wFunId);

            if (lObj) {
              lObj.value = getComputedValFn(computedValInListObj, dataList);
            }
          }
        }
      }

      if (list && list.length) {
        item.list = setDataListFn(item.list);
      }
    }

    return dataList;
  }

  return dataList;
};

const setDataFn = (obj = null) => {
  // console.log(obj);
  if (obj) {
    const data: any = toRaw(obj);

    if (data && data.list && data.list.length) {
      data['list'] = setDataListFn(data.list);
    }
  }

  item.value = obj;
};

const getLabelFn = item => {
  if (item) {
    const {
      labelZh = null,
      labelEn = null,
      labelRu = null,
      labelTrueZh = null,
      labelTrueEn = null,
      labelTrueRu = null,
      labelFalseZh = null,
      labelFalseEn = null,
      labelFalseRu = null,
      inputType = null,
      hiddenText = false
    } = item;

    if (hiddenText) {
      return '';
    }

    if (inputType === 'btnBool') {
      const itemVal = getReadFn(item) as any;

      if (itemVal !== '0') {
        return language.value === 'zh'
          ? itemVal
            ? labelTrueZh || labelTrueEn || labelTrueRu || labelZh || labelEn || labelRu || '-'
            : labelFalseZh || labelFalseEn || labelFalseRu || labelZh || labelEn || labelRu || '-'
          : language.value === 'ru'? itemVal
          ? labelTrueRu || labelTrueZh || labelTrueEn || labelRu || labelEn || labelZh || '-'
          : labelFalseRu || labelFalseZh || labelFalseEn || labelRu || labelEn || labelZh || '-' : itemVal
          ? labelTrueEn || labelTrueZh || labelTrueRu || labelEn || labelZh || labelRu || '-'
          : labelFalseEn || labelFalseZh || labelFalseRu || labelEn || labelZh || labelRu || '-';
      } else {
        return language.value === 'zh'
          ? labelZh || labelEn || labelRu
          : language.value === 'ru' ? labelRu || labelZh || labelEn
          : labelEn || labelZh || labelRu;
      }
    }

    if (labelZh || labelEn) {
      return language.value === 'zh' ? labelZh || labelEn || labelRu : language.value === 'ru' ? labelRu || labelZh || labelEn : labelEn || labelZh || labelRu;
    }
  }

  return '-';
};

const getReadFn = item => {
  if (item) {
    const { funId = null, inputType = null } = item;

    // let value = modbusData.value.find(item => item.funId === funId)?.value || 0;

    let value = modbusNewData.value[funId] || 0

    if (inputType === 'btnBool' || inputType === 'textBool' || inputType === 'btnBoolImg') {
      value = value === '1' ? true : false;

      item.value = value;

      return value;
    } else {
      value = value.toFixed(1);

      return Number(value);
    }
  }

  return '0';
};

// const writeFn = async (item, list: any = []) => {
//   if (item && item.funId) {
//     const obj: any = filterWriteObjFn(item);

//     if (obj) {
//       const {
//         updateClear = false,
//         value = null,
//         defaultValGetLocal = false,
//         funId = null,
//         updateClearFunId = null,
//         updateSetVal = null,
//         updateSetFunId = null,
//         inputType = null,
//         writeVal = null
//       } = item;

//       if (value !== null && provitClickFn && provitClickFn.value) {
//         let newVal = value;

//         if (inputType === 'btnBool') {
//           if (writeVal !== null) {
//             newVal = writeVal ? 'FF00' : '0000'
//           } else {
//             newVal = newVal ? '0000' : 'FF00';
//           }
//         }

//         await provitClickFn.value({ ...obj, value:newVal, addr: obj.offsetId });
//       }

//       if (updateSetFunId && updateSetVal !== null) {
//         setTimeout(() => {
//           if (updateSetFunId && list && list.length) {
//             list.every(lItem => {
//               if (lItem.funId === updateSetFunId) {
//                 lItem.value = updateSetVal;

//                 return false;
//               }

//               return true;
//             });
//           } else {
//             item.value = updateSetVal;
//           }
//         }, 2000);
//       } else if (updateClear) {
//         setTimeout(() => {
//           if (updateClearFunId && list && list.length) {
//             list.every(lItem => {
//               if (lItem.funId === updateClearFunId) {
//                 lItem.value = lItem.defaultValGetLocal
//                   ? getLocalByFunId(lItem.funId)
//                   : lItem.defaultVal || 0;

//                 return false;
//               }

//               return true;
//             });
//           } else {
//             item.value = defaultValGetLocal
//               ? getLocalByFunId(funId)
//               : item.defaultVal || 0;
//           }
//         }, 2000);
//       }
//     } else {
//       message.error(`找不到funId:${item.funId}的写入数据`);
//     }
//   } else {
//     message.error(!item ? '无写入数据' : '无funId');
//   }
// };

// const btnClickFn = (item, list) => {
//   if (item) {
//     const { funId = null, writeFunId = null } = item;

//     if (writeFunId && list && list.length) {
//       const writeItem = list.find(lItem => lItem.funId === writeFunId);

//       if (writeItem) {
//         writeFn(writeItem, list);
//       } else {
//         message.error(`找不到writeFunId:${writeFunId}的写入数据`);
//       }

//       return;
//     }

//     if (funId) {
//       writeFn(item, list);
//     } else {
//       message.error('无funId');
//     }
//   }
// };

// const inputUpdateFn = (val, item) => {
//   // console.log(val);

//   if (val && item) {
//     const { funId = null, valSetLocal = false } = item;

//     item.value = val.value || 0;

//     if (funId && valSetLocal) {
//       setLocalByFunId(funId, val.value || 0);
//     }
//   }
//   // console.log(item);
// };

// const inputBlurFn = (_e, item, list) => {
//   if (item.inputType === 'write' && item.blurChange) {
//     writeFn(item, list);
//   }
// };

const { data = null } = props;

const chooseItem: any = inject('chooseItem',null);

const machineData: any = inject('machineData',null);

if (data) {
  setDataFn(data);
}

// const setRefFn = (el: any, name: any, type: any) => {
//   if (el) {
//     const obj = {
//       name,
//       el
//     };

//     let list = type === 'print' ? drawerTemplateDataPrintRefList :drawerTemplateDataRefList;

//     const isAdd = list.every((item, key) => {
//       if (item.name === name) {
//         list[key] = obj;

//         return false;
//       }

//       return true;
//     });

//     if (isAdd) {
//       list.push(obj);
//     }
//   }
// };

const getDrawerTemplateInputDataFn = () => {
  const oChooseItem = chooseItem.value;

  const oMachineData = machineData.value;

  // console.log(item.value);

  // console.log(drawerTemplateInputRef.value)

  if (
    oChooseItem &&
    oMachineData &&
    drawerTemplateInputRef &&
    drawerTemplateInputRef.value &&
    (drawerTemplateInputRef.value.length || drawerTemplateInputRef.value.getDataFn)
  ) {
    const { materialCode = null, version = null } = oChooseItem;

    const { machineCode = null } = oMachineData;

    if (materialCode && version && machineCode) {
      const list: any = [];

      let parentDataLabelZh = '';

      if (item && item.value && item.value.labelZh) {
        parentDataLabelZh = `${item.value.labelZh}_`;
      }

      if (drawerTemplateInputRef.value.length) {
        // 多个
        for (const item of drawerTemplateInputRef.value) {
          const obj = toRaw(item.getDataFn()) || {};

          const { list: oList = [], labelZh: oLabelZh = null } = obj;

          if (obj && oList && oList.length) {
            for (const oItem of oList) {
              // console.log(oItem)
              const {
                inputType = null,
                value = '0',
                labelZh = null,
                funId = null,
                saveValByFunId = null,
                decimalPlaces = 0
              } = oItem;

              if (
                funId && (
                  inputType === 'readWrite' ||
                  inputType === 'write' ||
                  inputType === 'confirmWrite'
                )
              ) {
                let sr:any = !isNaN(Number(value)) ? Number(value) : 0;

                if (saveValByFunId) {
                  const obj = oList.find(oItem => oItem.funId === saveValByFunId);

                  if (obj) {
                    sr = !isNaN(Number(obj.value)) ? Number(obj.value) : 0;

                    // 小数位
                    if (decimalPlaces !== 0) {
                      let zero = '';

                      for (let i = 0; i < decimalPlaces; i++) {
                        zero += '0';
                      }

                      const num = Number(1 + zero);

                      if (!isNaN(num)) {
                        sr = sr * num;
                      }
                    }
                  }
                }

                list.push({
                  operatorMode: 'W',
                  machineCode,
                  version,
                  materialCode,
                  paramCode: funId,
                  paramName: `${parentDataLabelZh}${oLabelZh}_${labelZh}`,
                  sr
                });
              }
            }
          }
        }
      }

      if (drawerTemplateInputRef.value.getDataFn) {
        // 单个
        const obj = toRaw(drawerTemplateInputRef.value.getDataFn()) || {};

          const { list: oList = [], labelZh: oLabelZh = null } = obj;

          if (obj && oList && oList.length) {
            for (const oItem of oList) {
              // console.log(oItem)
              const {
                inputType = null,
                value = '0',
                labelZh = null,
                funId = null,
                saveValByFunId = null,
                decimalPlaces = 0
              } = oItem;

              if (
                funId && (
                  inputType === 'readWrite' ||
                  inputType === 'write' ||
                  inputType === 'confirmWrite'
                )
              ) {
                let sr:any = !isNaN(Number(value)) ? Number(value) : 0;

                if (saveValByFunId) {
                  const obj = oList.find(oItem => oItem.funId === saveValByFunId);

                  if (obj) {
                    sr = !isNaN(Number(obj.value)) ? Number(obj.value) : 0;

                    // 小数位
                    if (decimalPlaces !== 0) {
                      let zero = '';

                      for (let i = 0; i < decimalPlaces; i++) {
                        zero += '0';
                      }

                      const num = Number(1 + zero);

                      if (!isNaN(num)) {
                        sr = sr * num;
                      }
                    }
                  }
                }

                list.push({
                  operatorMode: 'W',
                  machineCode,
                  version,
                  materialCode,
                  paramCode: funId,
                  paramName: `${parentDataLabelZh}${oLabelZh}_${labelZh}`,
                  sr
                });
              }
            }
          }
      }



      return list;
    }
  }

  return [];
};

defineExpose({ setDataFn, getDrawerTemplateInputDataFn });
</script>
<style lang="less">
.drawerTemplateData {
  :deep(.n-input__input-el) {
    font-size: 18px !important;
    height: 40px !important;
    color: #222222;
  }

  // :deep(.n-button) {
  //   --n-border: none !important;
  //   --n-border-hover: none !important;
  //   --n-border-focus: none !important;
  //   --n-border-pressed: none !important;
  //   --n-border-disabled: none !important;
  //   --n-color-pressed: none !important;
  //   --n-color-focus: none !important;
  //   --n-color-hover: none !important;
  // }

  :deep(.n-button--primary-type) {
    min-width: 101px !important;
    height: 40px;
    // background: linear-gradient(
    //   180deg, #DCFFE5 5%, #52C570 87%
    // );
    // border-radius: 0px !important;
    // color: #4d4d4d;
    // border:0 !important;
    // // border: 2px solid #d9d9d9;
    // // border-image-source: linear-gradient(45deg, #5d5d5d, #aaabab);
    // border: 0px solid #757575;
    // border-image-slice: 1;
    // clip-path: inset(0 round 3px);
    font-size: 18px;
    // color: #222222;
  }
  :deep(.n-button:not(.n-button--disabled):hover) {
    color: #4d4d4d;
  }
  :deep(.n-button:not(.n-button--disabled):focus) {
    color: #4d4d4d;
  }

  .drawerTemplateData-view-price {
    display: flex;
    justify-content: space-between;
    margin: 0 20px;
  }

  .drawerTemplateData-view-content {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 20px;
    .drawerTemplateData-view-item {
      border-bottom: 0;
    }
    // padding: 30px 10px 0 20px;
  }

  .drawerTemplateData-view-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e8e8e8;
    font-size: 18px;
    width: 50%;

    .drawerTemplateData-view-item {
      width: auto;
    }

    .drawerTemplateData-view-item-w120 {
      width: 100px;
    }

    .drawerTemplateData-view-item-text {
      text-align: center;
      color: #307AFA;
    }

    .drawerTemplateData-view-item-text-reality {
      width: 100px;
      margin-right: 12px;
    }

    .drawerTemplateData-view-item-text-setup {
      width: 100px;
    }

    .drawerTemplateData-view-item-input {
      display: flex;
    }

    .drawerTemplateData-view-item-list {
      display: flex;
      flex: 1;
    }

    // .drawerTemplateData-view-item-input-margin {
    //   margin-right: 12px;
    // }

    .drawerTemplateData-view-item-input-write-number-confirm {
      margin-left: 12px;
    }

    .drawerTemplateData-view-item-input {
      color: #222222;
    }
    .drawerTemplateData-view-item-label {
      width: 100px;
    }
    .drawerTemplateData-view-item-read {
      width: 120px;
      margin-right: 15px;
    }
    .drawerTemplateData-view-item-input-read-val {
      width: 98px;
      height: 38px;
      background: #ebebeb;
      border-radius: 4px;
      border: 1px solid #d4d6d9;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      color: #222222;
    }
    .drawerTemplateData-view-item-input-write {
      display: flex;
      flex: 1;
    }

    .drawerTemplateData-view-item-input-write-number {
      width: 100px;
      border-radius: 4px !important;
    }
  }

  .drawerTemplateData-view-content-setting {
    .drawerTemplateData-view-item {
      width: auto !important;
    }
  }

  .drawerTemplateData-view-btn {
    padding: 10px 20px;
    display: flex;
    :deep(.drawerTemplateInput) {
      justify-content: space-around;
    }
  }

  .drawerTemplateData-view-btn-hidden-bottom-border {
    .drawerTemplateData-view-item {
      border-bottom: 0;
    }
  }
}
</style>
